package com.cykj.pos.controller.api;

import com.alibaba.fastjson.JSONObject;
import com.cykj.common.core.domain.AjaxResult;
import com.cykj.common.utils.SecurityUtils;
import com.cykj.pos.controller.TestDTO.FileItem;
import com.cykj.pos.controller.TestDTO.HttpClientHandler;
import com.cykj.pos.domain.BizMerchant;
import com.cykj.pos.domain.BizMerchantEntry;
import com.cykj.pos.domain.dto.BizAgentidAppkeyDTO;
import com.cykj.pos.domain.dto.BizEntrySnDTO;
import com.cykj.pos.domain.dto.BizTransactionCountDTO;
import com.cykj.pos.domain.posone.BizAreaCodeInfoDTO;
import com.cykj.pos.domain.posone.BizMerchantEntryDTO;
import com.cykj.pos.domain.posone.PosOneMerchantInfo;
import com.cykj.pos.profit.dto.MerchantDTO;
import com.cykj.pos.profit.dto.MerchantInfoDTO;
import com.cykj.pos.service.*;
import com.cykj.pos.service.impl.BizMerchantReceiverServiceImpl;
import com.cykj.pos.util.PosOneUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.codec.digest.DigestUtils;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/pos/api/v1/merchant")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@Api(tags = "我的商户")
public class PosV1AppMerchantController {
    private final IBizMerchantInfoService iBizMerchantInfoService;

    private final IBizMerchantEntryService bizMerchantEntryService;

    private final IBizMerchantService bizMerchantService;

    private final IBizPosMachineStatusRecordsService recordsService;

    private final IBizMerchantEntryService iBizMerchantEntryService;

    private final IBizPosMachineService iBizPosMachineService;

    private final IBizMerchTransactionsService bizMerchTransactionsService;

    private final BizMerchantReceiverServiceImpl bizMerchantReceiverService;

    /**
     * 查询我的商户
     *
     * @param merchantDTO
     * @return
     */
    @ApiOperation("我的商户")
    @PostMapping("/my/merch")
    public AjaxResult queryMyMerch(@RequestBody MerchantDTO merchantDTO) throws Exception {
        AjaxResult ajaxResult = AjaxResult.success("我的商户");
        // 查询商户数量
        int num = bizMerchantEntryService.queryMyMerchNum(merchantDTO.getUserId());
        // 查询商户信息
        List<PosOneMerchantInfo> list = bizMerchantEntryService.getPosOneMerchantInfo(merchantDTO);
        for (PosOneMerchantInfo pos : list) {
            if (!pos.getIsAudit().equals("3")) {// 除了审核成功的
                queryAuditStatus(merchantDTO.getUserId(), pos.getId());
            }
        }
        List<PosOneMerchantInfo> list1 = bizMerchantEntryService.getPosOneMerchantInfo(merchantDTO);
        ajaxResult.put("num", num);
        ajaxResult.put("data", list1);
        return ajaxResult;
    }

    // 查询我的商户的时候判断审核状态
    public final void queryAuditStatus(Long userId, String sn) throws Exception {
        BizMerchant bizMerchant = bizMerchantService.getMerchantByUserId(userId);
        BizMerchantEntry merchantEntry = bizMerchantEntryService.getBizMerchantEntryBySn(sn);
        BizAgentidAppkeyDTO bizAgentidAppkeyDTO= bizMerchantReceiverService.getAgentidAppkey(SecurityUtils.getLoginUser().getUser().getUserId());
        if (merchantEntry.getMerchantNo() != null) {
            //List<BizMerchantEntry> bizMerchantEntry = bizMerchantEntryService.getBizMerchantEntryByMerchId(bizMerchant.getMerchId());
            String url = "http://wx.wenwenpay.com.cn:6080/vipf/merchantinfo.do?action=handleAction&beanName=merchantinfoDao&Methods=load";
            //iBizMerchantInquiryService.postbizMerchantLnforSel(merchantInquiryDTO);
            Map<String, String> data = new HashMap<String, String>();
            data.put("merchant_no", merchantEntry.getMerchantNo());
            data.put("mersource", "OUTMER");
            data.put("agentid", bizAgentidAppkeyDTO.getAgentid());
            data.put("key", bizAgentidAppkeyDTO.getKey());
            data.put("sign", PosOneUtil.generateSignature(data));
            String result = HttpClientHandler.noPictureRequest(url, data);
            System.out.println("请求返回数据======" + result);
            JSONObject jsonObject = JSONObject.parseObject(result);
            String retCode = jsonObject.getString("ret_code");
            if (retCode.equals("0")) {
                // 查询成功 判断审核状态
                JSONObject data1 = jsonObject.getJSONObject("data");
                String proMerSub = data1.getString("pro_mer_sub");
                String proMerSubName = data1.getString("pro_mer_sub_name");
                if (proMerSubName.equals("审核成功")) {
                    // 更改审核状态 pos变成激活的
                    merchantEntry.setIsAudit(proMerSub);// 审核成功
                    Boolean row = bizMerchantEntryService.saveOrUpdate(merchantEntry);
                    int rec = recordsService.updateRecordsService(sn);
                } else {
                    // 审核失败 改状态 加上 失败原因
                    String ress4 = data1.getString("ress4");
                    // pos机状态不用改
                    // 存上失败信息
                    merchantEntry.setIsAudit(proMerSub);// 审核失败
                    merchantEntry.setErrorMsg(ress4);
                    Boolean row = bizMerchantEntryService.saveOrUpdate(merchantEntry);
                }
            }
        }
    }

    /**
     * 我的商户设备信息
     *
     * @return
     */
    @PostMapping("/queryEquipmentInfo")
    public AjaxResult queryMerchantEquipmentInfo(@RequestBody MerchantInfoDTO merchantInfoDTO) {
        AjaxResult ajaxResult = AjaxResult.success("我的商户设备信息");

        return ajaxResult;
    }

    @ApiOperation("查询我的商户交易笔数 交易量")
    @PostMapping("/queryMyCommercialTenant")
    @Transactional
    public AjaxResult queryMyCommercialTenant(@RequestBody BizMerchantEntry bizMerchantEntry) {
        AjaxResult ajaxResult = AjaxResult.success();
        SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM");
        String format = sdf.format(new Date());
        List<BizTransactionCountDTO> bizTerminalNoDTO =new ArrayList<BizTransactionCountDTO>();
        BizTransactionCountDTO merchName =  new BizTransactionCountDTO();

        if(bizMerchantEntry.getType()!=null&&bizMerchantEntry.getType()==2){
            bizTerminalNoDTO=iBizMerchantInfoService.selectBizMerchantInfoByMerchantNo(bizMerchantEntry);
            merchName=iBizMerchantInfoService.selectBizMerchantEntryMerchNameAndTime(bizMerchantEntry.getMerchantNo());
        }else{

            bizTerminalNoDTO = bizMerchantEntryService.selectBizMerchantEntryByMerchantNo(bizMerchantEntry);
            merchName =   bizMerchantEntryService.selectBizMerchantEntryMerchNameAndTime(bizMerchantEntry.getMerchantNo());
        }
        if(bizTerminalNoDTO.size() == 0){
            return AjaxResult.error("没有数据");
        }
        //查询本月交易额 交易笔数  总体交易额 交易笔数
        for (BizTransactionCountDTO list : bizTerminalNoDTO) {
            //查询总交易笔数和总交易量
            BizTransactionCountDTO bizTransactionCountDTO = bizMerchTransactionsService.selectCountBizMerchTransactions(list.getSn());
            //查询月交易量和与交易笔数
            BizTransactionCountDTO bizTransactionCountDTO1 = bizMerchTransactionsService.selectSumCountBizMerchTransactions(format, list.getSn());
            list.setSumCount(bizTransactionCountDTO.getSumCount());
            list.setSumAmount(bizTransactionCountDTO.getSumAmount());
            list.setMouthAmount(bizTransactionCountDTO1.getMouthAmount());
            list.setMouthCount(bizTransactionCountDTO1.getMouthCount());
        }
        ajaxResult.put("list", bizTerminalNoDTO);
        ajaxResult.put("data",merchName);
        return ajaxResult;
    }
    /**
     * 回显报件信息
     *
     * @return
     */
    @PostMapping("/query/entry")
    public AjaxResult queryBizMerchantEntry(@RequestBody MerchantInfoDTO merchantInfoDTO) {
        AjaxResult ajaxResult = AjaxResult.success("回显报件信息");
        if (merchantInfoDTO.getSnCode() == null) {
            BizMerchantEntry bizMerchantEntry = bizMerchantEntryService.getBizMerchantEntryByMerchantNo(merchantInfoDTO.getMerchantNo());
            BizMerchantEntryDTO bizMerchantEntryDTO = bizMerchantEntryService.getBizMerchantEntryInfoByByMerchantNo(merchantInfoDTO.getMerchantNo());
            BizAreaCodeInfoDTO bizAreaCodeInfoDTO = bizMerchantEntryService.getBizAreaCodeByCode(bizMerchantEntry.getProvinceno());// 省
            BizAreaCodeInfoDTO bizAreaCodeInfoDTO1 = bizMerchantEntryService.getBizAreaCodeByCode(bizMerchantEntry.getCityno());// 市
            BizAreaCodeInfoDTO bizAreaCodeInfoDTO2 = bizMerchantEntryService.getBizAreaCodeByCode(bizMerchantEntry.getAreano());// 区
            bizMerchantEntryDTO.setProvinceno(bizAreaCodeInfoDTO);
            bizMerchantEntryDTO.setCityno(bizAreaCodeInfoDTO1);
            bizMerchantEntryDTO.setAreano(bizAreaCodeInfoDTO2);
            BizAreaCodeInfoDTO feeId = bizMerchantEntryService.getFeeIdInfo(bizMerchantEntry.getFeeChlId());
            bizMerchantEntryDTO.setFeeChlId(feeId);
            ajaxResult.put("data", bizMerchantEntryDTO);
        } else {
            BizMerchantEntry bizMerchantEntry = bizMerchantEntryService.getBizMerchantEntryBySn(merchantInfoDTO.getSnCode());
            BizMerchantEntryDTO bizMerchantEntryDTO = bizMerchantEntryService.getBizMerchantEntryInfoBySn(merchantInfoDTO.getSnCode());
            BizAreaCodeInfoDTO bizAreaCodeInfoDTO = bizMerchantEntryService.getBizAreaCodeByCode(bizMerchantEntry.getProvinceno());// 省
            BizAreaCodeInfoDTO bizAreaCodeInfoDTO1 = bizMerchantEntryService.getBizAreaCodeByCode(bizMerchantEntry.getCityno());// 市
            BizAreaCodeInfoDTO bizAreaCodeInfoDTO2 = bizMerchantEntryService.getBizAreaCodeByCode(bizMerchantEntry.getAreano());// 区
            bizMerchantEntryDTO.setProvinceno(bizAreaCodeInfoDTO);
            bizMerchantEntryDTO.setCityno(bizAreaCodeInfoDTO1);
            bizMerchantEntryDTO.setAreano(bizAreaCodeInfoDTO2);
            BizAreaCodeInfoDTO feeId = bizMerchantEntryService.getFeeIdInfo(bizMerchantEntry.getFeeChlId());
            bizMerchantEntryDTO.setFeeChlId(feeId);
            ajaxResult.put("data", bizMerchantEntryDTO);
        }
        return ajaxResult;
    }

    /**
     * 修改报件信息
     *
     * @param bizMerchantEntry
     * @return
     * @throws Exception
     */
    @PostMapping("/update")
    @ApiOperation("修改报件")
    public AjaxResult updateBizMerchantEntry(@RequestBody BizMerchantEntry bizMerchantEntry) throws Exception {
        BizAgentidAppkeyDTO bizAgentidAppkeyDTO= bizMerchantReceiverService.getAgentidAppkey(SecurityUtils.getLoginUser().getUser().getUserId());
        AjaxResult ajaxResult = AjaxResult.success("修改报件信息");
        String url = "http://wx.wenwenpay.com.cn:6080/vipf/merchantinfo.do?action=handleAction&beanName=merchantinfoDao&Methods=update";
//        String url = "";
        Map<String, String> data = new HashMap<String, String>();
        // 商户编号我自己获取 通过设备号获取
        /*BizEntrySnDTO bizEntrySn = iBizMerchantEntryService.getBizEntrySn(bizMerchantEntry.getSn());
        bizMerchantEntry.setMerchantNo(bizEntrySn.getMerchantNo());*/
        data.put("merchant_no", bizMerchantEntry.getMerchantNo());
        data.put("account_id", bizMerchantEntry.getAccountId());
        data.put("provinceno", bizMerchantEntry.getProvinceno());
        data.put("cityno", bizMerchantEntry.getCityno());
        data.put("areano", bizMerchantEntry.getAreano());
        //data.put("address",bizMerchantEntry.getAddress());
        //data.put("certificateno", bizMerchantEntry.getCertificateno());
        data.put("certificatestartdate", bizMerchantEntry.getCertificatestartdate());
        data.put("certificateenddate", bizMerchantEntry.getCertificateenddate());
        data.put("bankcardaccount", bizMerchantEntry.getBankcardaccount());
        data.put("fee_chl_id", bizMerchantEntry.getFeeChlId());
        data.put("mersource", "OUTMER");
        data.put("agentid", bizAgentidAppkeyDTO.getAgentid());
        data.put("key", bizAgentidAppkeyDTO.getKey());
        data.put("sign", generateSignature(data));
        Map<String, FileItem> fileItemMap = new HashMap<>();
        FileItem idcardFront = new FileItem();
        idcardFront.setFileName("身份证头像面");
        idcardFront.setFile(convertFileByUrl(bizMerchantEntry.getIdcardfront()));

        FileItem idcardBack = new FileItem();
        idcardBack.setFileName("身份证国徽面");
        idcardBack.setFile(convertFileByUrl(bizMerchantEntry.getIdcardback()));

        FileItem bankcardFront = new FileItem();
        bankcardFront.setFileName("银行卡正面照");
        bankcardFront.setFile(convertFileByUrl(bizMerchantEntry.getBankcardfront()));

        FileItem bankcardBack = new FileItem();
        bankcardBack.setFileName("银行卡背面照");
        bankcardBack.setFile(convertFileByUrl(bizMerchantEntry.getBankcardback()));
        fileItemMap.put("idcardFront", idcardFront);
        fileItemMap.put("idcardBack", idcardBack);
        fileItemMap.put("bankcardFront", bankcardFront);
        fileItemMap.put("bankcardBack", bankcardBack);
        System.out.println(data);
        System.out.println(fileItemMap);
        String result = HttpClientHandler.onRequest(url, data, fileItemMap);
        System.out.println("商户修改返回:" + result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        String ret_code = jsonObject.getString("ret_code");
        String msg = jsonObject.getString("ret_msge");
        if (ret_code.equals("0")) {
            // 更改一下报件信息
            deleteFile(idcardFront.getFile());
            deleteFile(idcardBack.getFile());
            deleteFile(bankcardFront.getFile());
            deleteFile(bankcardBack.getFile());
            bizMerchantEntry.setIsAudit("0");// 审核中
            int row = bizMerchantEntryService.updateizMerchantEntry(bizMerchantEntry);
           // recordsService.updateRecordsStatus(bizMerchantEntry.getSn());//修改激活表状态为 未激活
           // iBizPosMachineService.updatePosMachine(bizMerchantEntry.getSn());//修改设备表状态为 未激活
            ajaxResult.put("data", true);
            ajaxResult.put("msg", msg);
        } else {
            deleteFile(idcardFront.getFile());
            deleteFile(idcardBack.getFile());
            deleteFile(bankcardFront.getFile());
            deleteFile(bankcardBack.getFile());
            ajaxResult.put("data", false);
            ajaxResult.put("msg", msg);
        }
        //查询商户状态
        String urls = "http://wx.wenwenpay.com.cn:6080/vipf/merchantinfo.do?action=handleAction&beanName=merchantinfoDao&Methods=load";
        Map<String, String> dataMap = new HashMap<String, String>();
        dataMap.put("merchant_no", bizMerchantEntry.getMerchantNo());
        dataMap.put("mersource", "OUTMER");
        dataMap.put("agentid", bizAgentidAppkeyDTO.getAgentid());
        dataMap.put("key", bizAgentidAppkeyDTO.getKey());
        dataMap.put("sign", PosOneUtil.generateSignature(dataMap));
        String results = HttpClientHandler.noPictureRequest(urls, dataMap);
        System.out.println("查询商户状态返回数据======" + results);
        JSONObject parseObject = JSONObject.parseObject(results);
        String code = parseObject.getString("ret_code");
        if (code.equals("0")) {
            //获取审核状态
            JSONObject data1 = parseObject.getJSONObject("data");
            String proMerSub = data1.getString("pro_mer_sub");
            //更新商户入件状态
            bizMerchantEntryService.updateMerchantEntry(bizMerchantEntry.getMerchantNo(), proMerSub);
            String proMerSubName = data1.getString("pro_mer_sub_name");
            ajaxResult.put("retMsge", proMerSubName);
        }
        return ajaxResult;
    }


    /**
     * pc端修改报件信息
     *
     * @param bizMerchantEntry
     * @return
     * @throws Exception
     */
    @PostMapping("/updatePc")
    @ApiOperation("pc端修改报件")
    public AjaxResult updatePCBizMerchantEntry(@RequestBody BizMerchantEntry bizMerchantEntry) throws Exception {
        BizAgentidAppkeyDTO bizAgentidAppkeyDTO= bizMerchantReceiverService.getAgentidAppkey(SecurityUtils.getLoginUser().getUser().getUserId());
        AjaxResult ajaxResult = AjaxResult.success("修改报件信息");
        String url = "http://wx.wenwenpay.com.cn:6080/vipf/merchantinfo.do?action=handleAction&beanName=merchantinfoDao&Methods=update";
//        String url = "";
        Map<String, String> data = new HashMap<String, String>();
        data.put("merchant_no", bizMerchantEntry.getMerchantNo());
        data.put("account_id", bizMerchantEntry.getAccountId());
        data.put("provinceno", bizMerchantEntry.getProvinceno());
        data.put("cityno", bizMerchantEntry.getCityno());
        data.put("areano", bizMerchantEntry.getAreano());
        //data.put("address",bizMerchantEntry.getAddress());
        //data.put("certificateno", bizMerchantEntry.getCertificateno());
        data.put("certificatestartdate", bizMerchantEntry.getCertificatestartdate());
        data.put("certificateenddate", bizMerchantEntry.getCertificateenddate());
        data.put("bankcardaccount", bizMerchantEntry.getBankcardaccount());
        data.put("fee_chl_id", bizMerchantEntry.getFeeChlId());
        data.put("mersource", "OUTMER");
        data.put("agentid", bizAgentidAppkeyDTO.getAgentid());
        data.put("key", bizAgentidAppkeyDTO.getKey());
        data.put("sign", generateSignature(data));
        Map<String, FileItem> fileItemMap = new HashMap<>();
        FileItem idcardFront = new FileItem();
        idcardFront.setFileName("身份证头像面");
        idcardFront.setFile(convertFileByUrl(bizMerchantEntry.getIdcardfront()));

        FileItem idcardBack = new FileItem();
        idcardBack.setFileName("身份证国徽面");
        idcardBack.setFile(convertFileByUrl(bizMerchantEntry.getIdcardback()));

        FileItem bankcardFront = new FileItem();
        bankcardFront.setFileName("银行卡正面照");
        bankcardFront.setFile(convertFileByUrl(bizMerchantEntry.getBankcardfront()));

        FileItem bankcardBack = new FileItem();
        bankcardBack.setFileName("银行卡背面照");
        bankcardBack.setFile(convertFileByUrl(bizMerchantEntry.getBankcardback()));
        fileItemMap.put("idcardFront", idcardFront);
        fileItemMap.put("idcardBack", idcardBack);
        fileItemMap.put("bankcardFront", bankcardFront);
        fileItemMap.put("bankcardBack", bankcardBack);
        System.out.println(data);
        System.out.println(fileItemMap);
        String result = HttpClientHandler.onRequest(url, data, fileItemMap);
        System.out.println("商户修改返回:" + result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        String ret_code = jsonObject.getString("ret_code");
        String msg = jsonObject.getString("ret_msge");
        if (ret_code.equals("0")) {
            // 更改一下报件信息
            deleteFile(idcardFront.getFile());
            deleteFile(idcardBack.getFile());
            deleteFile(bankcardFront.getFile());
            deleteFile(bankcardBack.getFile());
            bizMerchantEntry.setIsAudit("0");// 审核中
            int row = bizMerchantEntryService.updateizMerchantEntry(bizMerchantEntry);
          //  recordsService.updateRecordsStatus(bizMerchantEntry.getSn());//修改激活表状态为 未激活
          //  iBizPosMachineService.updatePosMachine(bizMerchantEntry.getSn());//修改设备表状态为 未激活
            ajaxResult.put("data", true);
            ajaxResult.put("msg", msg);
        } else {
            deleteFile(idcardFront.getFile());
            deleteFile(idcardBack.getFile());
            deleteFile(bankcardFront.getFile());
            deleteFile(bankcardBack.getFile());
            ajaxResult.put("data", false);
            ajaxResult.put("msg", msg);
        }
        //查询商户状态
        String urls = "http://wx.wenwenpay.com.cn:6080/vipf/merchantinfo.do?action=handleAction&beanName=merchantinfoDao&Methods=load";
        Map<String, String> dataMap = new HashMap<String, String>();
        dataMap.put("merchant_no", bizMerchantEntry.getMerchantNo());
        dataMap.put("mersource", "OUTMER");
        dataMap.put("agentid", bizAgentidAppkeyDTO.getAgentid());
        dataMap.put("key", bizAgentidAppkeyDTO.getKey());
        dataMap.put("sign", PosOneUtil.generateSignature(dataMap));
        String results = HttpClientHandler.noPictureRequest(urls, dataMap);
        System.out.println("查询商户状态返回数据======" + results);
        JSONObject parseObject = JSONObject.parseObject(results);
        String code = parseObject.getString("ret_code");
        if (code.equals("0")) {
            //获取审核状态
            JSONObject data1 = parseObject.getJSONObject("data");
            String proMerSub = data1.getString("pro_mer_sub");
            //更新商户入件状态
            bizMerchantEntryService.updateMerchantEntry(bizMerchantEntry.getMerchantNo(), proMerSub);
            String proMerSubName = data1.getString("pro_mer_sub_name");
            ajaxResult.put("retMsge", proMerSubName);
        }
        return ajaxResult;
    }

    public static String generateSignature(Map<String, String> data) throws Exception {
        Set<String> keySet = data.keySet();
        String[] keyArray = keySet.toArray(new String[keySet.size()]);
        Arrays.sort(keyArray);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < keyArray.length; i++) {
            String k = keyArray[i];
            if (data.get(k) != null) { // 参数值为空，则不参与签名
                sb.append(k).append("=").append(data.get(k).trim());
                if (i != keyArray.length - 1) {
                    sb.append("&");
                }
            }
        }
        return md5(sb.toString()).toUpperCase();
    }

    /*//**
     * 方法描述:将字符串MD5加码 生成32位md5码
     *
     * @author leon 2016年10月10日 下午3:02:30
     * @param inStr
     * @return
     */
    public static String md5(String inStr) {
        try {
            return DigestUtils.md5Hex(inStr.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("MD5签名过程中出现错误");
        }
    }

    public static File convertFileByUrl(String url) {
        //对本地文件命名
        String fileName = url.substring(url.lastIndexOf("."), url.length());
        File file = null;
        URL urlfile;
        InputStream inStream = null;
        OutputStream os = null;
        try {
            file = File.createTempFile("net_url", fileName);
            //下载
            urlfile = new URL(url);
            inStream = urlfile.openStream();
            os = new FileOutputStream(file);

            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = inStream.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != os) {
                    os.close();
                }
                if (null != inStream) {
                    inStream.close();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return file;
    }

    /*
     * 如果是文件 ==》直接删除
     * 如果是目录 ==》必须先删除里面每一层目录里的所有文件，最后才能删除外层的目录
     *              原因：不为空的话 删不了
     */
    public static void deleteFile(File file) {
        if (file.exists()) {//判断路径是否存在
            if (file.isFile()) {//boolean isFile():测试此抽象路径名表示的文件是否是一个标准文件。
                file.delete();
            } else {//不是文件，对于文件夹的操作
                //保存 路径D:/1/新建文件夹2  下的所有的文件和文件夹到listFiles数组中
                File[] listFiles = file.listFiles();//listFiles方法：返回file路径下所有文件和文件夹的绝对路径
                for (File file2 : listFiles) {
                    /*
                     * 递归作用：由外到内先一层一层删除里面的文件 再从最内层 反过来删除文件夹
                     *    注意：此时的文件夹在上一步的操作之后，里面的文件内容已全部删除
                     *         所以每一层的文件夹都是空的  ==》最后就可以直接删除了
                     */
                    deleteFile(file2);
                }
            }
            file.delete();
        } else {
            System.out.println("该file路径不存在！！");
        }
    }

}
